// store/myModule.js
import WebSocketClient from '@/socket/soket.js';
import emojiUtils from '@/common/emoji.js'
import sqlInstance from '@/sqlite';
import friendSqlite from '@/sqlite_services/friend.js'
import msgSqlite from '@/sqlite_services/msg.js'
import seesionSqlite from '@/sqlite_services/seesion.js'
import friendApi from '@/services/api/friends.js'
const IOSXJPluginIOSPhotoModel = uni.requireNativePlugin("IOSXJPlugin-IOSPhotoModel")
import tuicallKitManager from "@/common/txTrc.js"
import mediaCache from '@/common/mediacache/mediaCache.js'; // 适配你的实际路径
export default {
	state: {
		user_info: {},
		socket: null,
		sqlite: null,
		deviceInfo:{},
	},
	mutations: {
		setDeviceInfo(state, data) {
			state.deviceInfo = data
		},
		setUserInfo(state, data) {
			let newdata = Object.assign({}, state.user_info, data)
			state.user_info = JSON.parse(JSON.stringify(newdata))
		},
		setUserInfoAssign(state, data) {
			state.user_info = data
		},
		COLSE_SOCKET(state) {
			state.socket && state.socket.close()
			state.socket = null
		},
		SET_SOCKET(state, socket) {
			state.socket = socket;
		},
		SET_SQLITE(state, sqlite) {
			state.sqlite = sqlite;
		},
	},
	actions: {
		//更新用户信息
		uploadUserInfo({
			dispatch,
			commit,
			state
		}, data) {
			commit('setUserInfo', data)
			console.log(state.user_info);
			uni.setStorageSync('user', JSON.stringify(state.user_info))
		},
		loginNest({
			state,
			dispatch,
			commit,
			rootState
		}, {data,requestError = true}) {
			console.log('***************---',requestError);
			return new Promise(async (resolve, reject) => {
				commit('COLSE_SOCKET');//关闭socket
				try{
					await dispatch('COLSE_SQLITE');
				}catch(e){
				}
				
				// 存储token到本地存储中
				uni.setStorageSync('token', data.access_token)
				uni.setStorageSync('refresh_token', data.refresh_token)

				//更新用户信息
				dispatch('uploadUserInfo', data.user_info)
				//更新平台信息
				dispatch('uploadPlatInfo', data.plat_info)
				
				try {
					console.log('正在连接本地数据库');
					//打开或创建此人数据库
					let sqlite = new sqlInstance()
					await sqlite.init({
						name: data.user_info.user_id,
						path: `_doc/${data.user_info.user_id}.db`
					})
					console.log(sqlite);
					commit('SET_SQLITE', sqlite);
					console.log('正在获取本地好友信息');
					let res = await friendSqlite.getFrindList()
					//直接赋值
					commit('setFriendList', res)
					//得到会话
					console.log('正在获取会话');
					let list = await seesionSqlite.getSesstion()
					if (list) {
						commit('setSeesion', list);
					}
				} catch (e) {
					console.log(e);
				}
				console.log('正在连接socket');
				if(!state.socket){
					let socket = WebSocketClient.getInstance(uni.$config.socketUrls);
					socket.connect(true)
					commit('SET_SOCKET', socket);
				}
				try{
					await tuicallKitManager.init(data.user_info)
					const MediaUrl = await mediaCache.loadMediaUrl(data.user_info.avatar_url, 'avatar', 'image');
					const parts = MediaUrl.split("?");
					await tuicallKitManager.setInfo(data.user_info.nick_name,parts[0] || '')
				}catch(e){
				}
				

				//初始化api好友这样做因为没有离线消息，所以每次重新拉取一下
				try {
					console.log('正在请求好友列表');
					let res = await friendApi.friendList(requestError)
					if (res) {
						dispatch('setFriendList', res.list)
					}
				} catch (e) {
					console.log(e);
				}
				//好友数量
				try {
					console.log('正在获取新好友数量');
					let applyres = await uni.$api.friends.applyList({
						page: 1,
						limit: 1
					},requestError)
					if(applyres && applyres.code == 200){
						 dispatch('updateFriendBadge',{ type: 'set', count:applyres.data.total})
					}
				} catch (e) {
					console.log(e);
				}
				
				console.log('开始获取我的客服');
				//获取我的客服
				try{
					await dispatch('getMyKefu')
				}catch(e){}
				console.log('开始查询在线好友');
				dispatch('startOnlineFriendTimer')
				
				//所有发送中的消息改为发送失败
				console.log('处理遗留发送中的消息');
				try{
					await msgSqlite.editSendState()
				}catch(e){
					//TODO handle the exception
				}
				
				console.log('正在获取聊天表情');
				try {
					emojiUtils.checkAndDownloadEmojis()
				} catch (e) {
					console.log(e);
				}
				resolve()
			})
		},

		//初始化登录
		initLogin({
			state,
			dispatch,
			commit,
			rootState
		},requestError = true) {
			return new Promise(async (resplve, reject) => {
				const token = uni.getStorageSync('token')
				const refresh_token = uni.getStorageSync('refresh_token')
				const userinfo = uni.getStorageSync('user')
				const platinfo = uni.getStorageSync('plat')
				
				if (token && refresh_token && userinfo && platinfo) {
					//因为是刚取出来所以就不要再存储了
					let user_info = JSON.parse(userinfo)
					let plat_info = JSON.parse(platinfo)
					console.log(plat_info);
					console.log(user_info);
					commit('setUserInfo', user_info)
					commit('setPlatInfo', platinfo)
					try {
						let apires = await uni.$api.user.info()
						if(apires){
							user_info = {...user_info,...apires.data}
							//更新用户信息
							dispatch('uploadUserInfo', apires.data)
						}
					} catch (e) {
						console.log(e);
						//TODO handle the exception
					}
					try {
						let platres = await uni.$api.user.platinfo(requestError)
						if (platres) {
							dispatch('uploadPlatInfo', platres.data)
						}
					} catch (e) {
						console.log(e);
						//TODO handle the exception
					}

					try {
						//打开或创建此人数据库
						console.log(1111,user_info);
						let sqlite = new sqlInstance()
						await sqlite.init({
							name: user_info.user_id,
							path: `_doc/${user_info.user_id}.db`
						})
						console.log(2222);
						commit('SET_SQLITE', sqlite);
						let res = await friendSqlite.getFrindList()
						//直接赋值
						commit('setFriendList', res)
						console.log(3333);
						//得到会话
						let list = await seesionSqlite.getSesstion()
						if (list) {
							commit('setSeesion', list);
						}
						console.log(4444);
					} catch (e) {
						console.log(e);
					}
					
					let socket = WebSocketClient.getInstance(uni.$config.socketUrls);
					socket.connect(true)
					commit('SET_SOCKET', socket);
					
					try{
						await tuicallKitManager.init(user_info)
						const MediaUrl = await mediaCache.loadMediaUrl(user_info.avatar_url, 'avatar', 'image');
						const parts = MediaUrl.split("?");
						await tuicallKitManager.setInfo(user_info.nick_name,parts[0]||'')
					}catch(e){
						
					}

					//初始化api好友这样做因为没有离线消息，所以每次重新拉取一下
					try {
						let res = await friendApi.friendList(requestError)
						if (res) {
							dispatch('setFriendList', res.list)
						}
					} catch (e) {
						console.log(e);
					}
					
					//好友数量
					try {
						let applyres = await uni.$api.friends.applyList({
							page: 1,
							limit: 1
						},requestError)
						if(applyres && applyres.code == 200){
							 dispatch('updateFriendBadge',{ type: 'set', count:applyres.data.total})
						}
					} catch (e) {
						console.log(e);
					}
					
					//获取我的客服
					try{
						await dispatch('getMyKefu')
					}catch(e){}
					
					dispatch('startOnlineFriendTimer')
					
					//所有发送中的消息改为发送失败
					try{
						await msgSqlite.editSendState()
					}catch(e){
						//TODO handle the exception
					}
					
					try {
						emojiUtils.checkAndDownloadEmojis()
					} catch (e) {
						console.log(e);
					}
					resplve()
				} else {
					reject()
				}
			})
		},
		//自动注册或登录
		autoLogin({
			state,
			dispatch,
			commit,
			rootState
		},requestError = true) {
			return new Promise(async (resplve, reject) => {
				try{
					let loginRes = await uni.$api.user.autologin(state.deviceInfo,requestError)
					if(loginRes && loginRes.code == 200){
						 let accountInfo = JSON.parse(JSON.stringify(loginRes.data.user_info))
						 accountInfo.login_type = 'auto'
						 let accounts = uni.getStorageSync('accounts') || [];
						 const index = accounts.findIndex(account => account.login_name == accountInfo.login_name);
						 if (index !== -1) {
						     accounts[index] = accountInfo;
						 } else {
						     accounts.push(accountInfo);
						 }
						 uni.setStorageSync('accounts', accounts);
						 if(requestError){
							uni.showLoading({
								title: getApp().$t("api.loading.msg.loginNest")
							})	
						 }
						 try{
						 	await dispatch('loginNest', {
								 data:loginRes.data,
								 requestError
						 	})
						 }catch(e){
						 	//TODO handle the exception
						 }
						 if(requestError){
							uni.hideLoading()
						 }
						 resplve()
						 return
					}
					reject('接口返回失败')
				}catch(e){
					reject(e)
					//TODO handle the exception
				}
			})
		},
		//退出登录
		logOut({
			state,
			dispatch,
			commit,
			rootState
		}) {
			try{
				dispatch('stopOnlineFriendTimer');
				commit('COLSE_SOCKET');
				dispatch('COLSE_SQLITE');
				uni.removeStorageSync('token')
				uni.removeStorageSync('refresh_token')
				uni.removeStorageSync('user')
				uni.removeStorageSync('plat')
				commit('setUserInfoAssign', {})
				commit('setPlatInfoAssign', {})
			}catch(e){
				//TODO handle the exception
			}

			// 跳转到登录页
			uni.reLaunch({
				url: "/pages/login/login"
			})
		},
		async COLSE_SQLITE({
			state,
			dispatch,
			commit,
			rootState
		}){
			if(state.sqlite){
				try{
					await state.sqlite.close()
				}catch(e){
					
				}
			}
			commit('SET_SQLITE', null);
		}
	}
};